import type { ReqGetUserInfoResponseData, ReqLoginRequestParams } from '@/api/interface/userInfo'
import userInfoApi from '@/api/userInfo'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import router from '@/router'

// userInfo仓库数据的接口
interface ReqUserInfoStoreState {
  token: string
  userInfo: ReqGetUserInfoResponseData
  menuRoutes: RouteRecordRaw[]
}

// 根据返回的路由名称数组过滤动态路由
const filterAllAsyncRoutes = (allAsyncRoutes: RouteRecordRaw[], routes: string[]) => {
  return allAsyncRoutes.filter((item) => {
    if (routes.indexOf(item.name as string) !== -1) {
      if (item.children && item.children.length) {
        filterAllAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}

// 动态添加路由
const addRoutes = (routeList: RouteRecordRaw[]) => {
  routeList.forEach((item) => {
    router.addRoute(item)
  })
}

// 重置路由
const resetRoutes = (routes: RouteRecordRaw[]) => {
  routes.forEach((item) => {
    router.removeRoute(item.name as string)
  })
}

export const useUserInfoStore = defineStore('userInfo', {
  state(): ReqUserInfoStoreState {
    return {
      // token
      token: localStorage.getItem('token_key') || '',
      // 用户信息
      userInfo: {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: ''
      },
      // 菜单路由
      menuRoutes: staticRoutes
    }
  },

  actions: {
    // 登录
    async login({ password, username }: ReqLoginRequestParams) {
      try {
        const data = await userInfoApi.reqLogin({ password, username })
        // console.log(data)
        this.token = data.token
        localStorage.setItem('token_key', data.token)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 获取用户信息
    async getUserInfo() {
      try {
        const data = await userInfoApi.reqGetUserInfo()
        // console.log(data)
        this.userInfo = data
        const userAsyncRoutes = filterAllAsyncRoutes(allAsyncRoutes, data.routes)
        addRoutes(userAsyncRoutes.concat(anyRoute))
        this.menuRoutes = staticRoutes.concat(userAsyncRoutes, anyRoute)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 退出登录
    async logout() {
      try {
        await userInfoApi.reqLoginout()
        localStorage.removeItem('token_key')
        this.token = ''
        const resetUserInfo = {
          routes: [],
          buttons: [],
          roles: [],
          name: '',
          avatar: ''
        }
        Object.assign(this.userInfo, resetUserInfo)
        const routes = router.getRoutes()
        resetRoutes(routes)
        addRoutes(staticRoutes)
        this.menuRoutes = staticRoutes
      } catch (error) {
        return Promise.reject(error)
      }
    }
  },

  getters: {}
})
